'''
Created on Nov 17, 2009

@author: mkiyer
'''

import os
import sys

from veggie.app.application import CommandLineApplication
from veggie.app.alignment import sw_root
import logging

_java_cmd = ['java', '-Xmx2g', '-jar']
_picard_root = os.path.join(sw_root, 'picard', 'current')
    

class MergeSamFiles(CommandLineApplication):
    _merge_cmd = os.path.join(_picard_root, 'MergeSamFiles.jar')
    _executable = ' '.join([' '.join(_java_cmd), _merge_cmd])

    def run(self, insamfiles, outsamfile, force=False):
        logger = logging.getLogger('Picard')
        if os.path.exists(outsamfile):
            logger.debug('%s: merged file %s exists' % (self.__class__.__name__,
                                                        outsamfile))
            if not force:
                logger.debug('%s: skipping merge' % (self.__class__.__name__))
                return 0, None
        tmp_path = os.path.abspath(os.path.dirname(outsamfile))
        merge_args = []
        for insamfile in insamfiles:
            merge_args.append("INPUT=%s" % insamfile)
        merge_args.extend(['OUTPUT=%s' % (outsamfile), 
                           'SORT_ORDER=coordinate',
                           'ASSUME_SORTED=false',
                           'MERGE_SEQUENCE_DICTIONARIES=false',
                           'VALIDATION_STRINGENCY=SILENT',
                           'TMP_DIR=%s' % (tmp_path)])
        self.args = merge_args
        return self()

    
class MarkDuplicates(CommandLineApplication):

    _markdups_cmd = os.path.join(_picard_root, 'MarkDuplicates.jar')
    _executable = ' '.join([' '.join(_java_cmd), _markdups_cmd])

    def run(self, insamfile, outsamfile, force=False):
        logger = logging.getLogger('Picard')
        if os.path.exists(outsamfile):
            logger.debug('%s: marked duplicates file %s exists' % (self.__class__.__name__,
                                                                   outsamfile))
            if not force:
                logger.debug('%s: skipping mark duplicates' % (self.__class__.__name__))
                return 0, None

        metricsfile = os.path.splitext(outsamfile)[0] + '.metrics.txt'
        args = ['I=%s' % (insamfile),
                'O=%s' % (outsamfile),
                'M=%s' % (metricsfile),
                'REMOVE_DUPLICATES=true',
                'VALIDATION_STRINGENCY=SILENT',
                'VERBOSITY=DEBUG',
                'QUIET=false']
        self.args = args
        return self()     
#        markdup_args = ['INPUT=%s' % (insamfile),
#                        'OUTPUT=%s' % (outsamfile),
#                        'METRICS_FILE=%s' % (metricsfile)]
#                        'VALIDATION_STRINGENCY=SILENT']

